/**
 * 展开JSON格式内容
 * 非拷贝
 * 如果
 * [
 *  id: 1,
 *  xx: xx
 *  children: []    //需要展开的内容
 * ]
 * list 需要展开对象数组
 * idKey 展开对象KEY，防止展开后的内容有重复
 * childrenKey 需要展开的内容的字段名
 * includeParentNode 是否包含含有子元素的父元素节点
 */
export function flatJSONList(
  list,
  idKey = 'id',
  childrenKey = 'children',
  includeParentNode = false
) {
  if (!list) return;
  let res = [];
  list.forEach(item =>
    flatJSONListNode(item, res, idKey, childrenKey, includeParentNode)
  );
  return res;
}
function flatJSONListNode(item, res, idKey, childrenKey, includeParentNode) {
  if (item[childrenKey] && item[childrenKey].length) {
    if (includeParentNode && !res.find(d => d[idKey] == item[idKey]))
      res.push(item);
    item[childrenKey].forEach(d =>
      flatJSONListNode(d, res, idKey, childrenKey, includeParentNode)
    );
  } else if ((item.isGroup && includeParentNode) || !item.isGroup) {
    if (!res.find(d => d[idKey] == item[idKey])) res.push(item);
  }
}

// 跟上面相同，直接把key作为数组下标
export function flatJSONListToKeyArray(
  list,
  idKey = 'id',
  childrenKey = 'children',
  includeParentNode = false
) {
  if (!list) return;
  let res = [];
  list.forEach(item =>
    flatJSONListNodeToKeyArray(item, res, idKey, childrenKey, includeParentNode)
  );
  return res;
}
function flatJSONListNodeToKeyArray(
  item,
  res,
  idKey,
  childrenKey,
  includeParentNode
) {
  if (item[childrenKey] && item[childrenKey].length) {
    if (includeParentNode) res[item[idKey]] = item;
    item[childrenKey].forEach(d =>
      flatJSONListNodeToKeyArray(d, res, idKey, childrenKey, includeParentNode)
    );
  } else if ((item.isGroup && includeParentNode) || !item.isGroup) {
    if (item[idKey]) res[item[idKey]] = item;
  }
}

// 迭代列表数据(所有节点跌点)
// data: Array。
// childrenKey: 子数据组对应的键
// cb: 回调，第一个参数为当前节点的全部数据
export function iterationListData(data, cb, childrenKey = 'children') {
  if (!data) return;
  data.forEach(d => {
    if (d[childrenKey] && d[childrenKey].length)
      iterationListData(d[childrenKey], cb, childrenKey);
    cb(d);
  });
}

//标准时间格式转换
export function formatTime(dateData) {
  if (dateData) {
    var date = new Date(dateData);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? '0' + m : m;
    var d = date.getDate();
    d = d < 10 ? '0' + d : d;
    var s = date.getHours();
    s = s < 10 ? '0' + s : s;
    var f = date.getMinutes();
    f = f < 10 ? '0' + f : f;
    var z = date.getSeconds();
    z = z < 10 ? '0' + z : z;
    const time = y + '-' + m + '-' + d + ' ' + s + ':' + f + ':' + z;
    return time;
  }
  return;
}
